<?php

namespace api\mobile;

use app\common\model\Mobile;
use think\facade\Db;

/**
 * 山东晨也信息9折慢充.[这家跪了]
 */
class Chenye extends BaseModel
{
    private $header = [
        'Content-Type: application/x-www-form-urlencoded',
    ];

    private $productIdMap = [
        50 => 16,
        100 => 17,
        200 => 18,
    ];

    /**
     * 创建订单.
     *
     * @params
     * sub_order_id 系统订单号
     * amount 充值金额
     * mobile 充值号码
     *
     * $return  false/供应商订单号
     */
    public function create($order)
    {
        $amount = fen2yuan($order['amount']);
        $params = [
            'out_trade_num' => $order['sub_order_id'],
            'product_id' => $this->productIdMap[$amount],
            'mobile' => $order['mobile'],
            'userid' => $this->info['app_id'],
            'notify_url' => $this->notifyUrl,
        ];
        $params['sign'] = $this->getSign($params);
        $url = $this->info['url'] . '/index/recharge';
        $res = curlPost($url, http_build_query($params), $this->header, 5, true);
        $res = json_decode($res, true);

        $supplier_order_no = '';
        $remark = $res['errmsg'] ?? '';
        if (!isset($res['errno'])) {
            $status = self::NEED_RETRY;
        } elseif ($res['errno'] == '0') {
            $supplier_order_no = $res['data']['order_number'];
            $status = self::SUCCESS;
        } else {
            $status = self::FAIL;
        }

        return compact('status', 'supplier_order_no', 'remark');
    }

    /**
     * 查询余额.
     *
     * 单位：分
     */
    public function queryAmount()
    {
        $params = [
            'userid' => $this->info['app_id'],
        ];
        $params['sign'] = $this->getSign($params);
        $url = $this->info['url'] . '/index/user';
        $res = curlPost($url, http_build_query($params), $this->header);
        $res = json_decode($res, true);
        if (!isset($res['data']['balance'])) {
            $this->error = $res['data']['errmsg'] ?? '查询频繁';

            return false;
        }

        return yuan2fen($res['data']['balance']);
    }

    /**
     * 订单查询.
     */
    public function query($orderId)
    {
        $params = [
            'userid' => $this->info['app_id'],
            'out_trade_nums' => $orderId,
        ];
        $params['sign'] = $this->getSign($params);
        $url = $this->info['url'] . '/index/check';
        $res = curlPost($url, http_build_query($params), $this->header);
        $res = json_decode($res, true);

        return $res;
    }

    /**
     * 生成签名.
     */
    public function getSign($params)
    {
        if (isset($params['sign'])) {
            unset($params['sign']);
        }
        ksort($params);
        // 拼接签名串
        $sign_str = http_build_query($params) . '&apikey=' . $this->info['app_secret'];
        // 签名
        $sign = strtoupper(md5(urldecode($sign_str)));

        return $sign;
    }

    /**
     * 订单回调.
     */
    public function notify($params)
    {
        $insert = [
            'sub_order_id' => $params['out_trade_num'] ?? '',
            'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'result' => 'success',
        ];

        $sign = $params['sign'] ?? '';
        $checkSign = $this->getSign($params);
        if ($sign !== $checkSign) {
            $insert['result'] = '验签失败';
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        $order = Db::name('mobile_order')
            ->where('sub_order_id', $params['out_trade_num'])
            ->where('mobile_supplier_id', $this->info['id'])
            ->where('mobile', $params['mobile'])
            ->find();
        if (empty($order)) {
            $insert['result'] = '订单不存在';
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        if (in_array($order['supplier_status'], [3, 4, 99])) {
            // if ($order['supplier_status'] == 3) {
            $insert['result'] = '已经成功过';
            Db::name('mobile_notify')->insert($insert);

            return 'success';
        }

        if ($order['supplier_status'] != 2) {
            $insert['result'] = '订单状态有误：' . $order['supplier_status'];
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        // 供应商订单状态：1订单未创建 2订单已创建 3充值成功 4充值失败
        // 0表示充值中; 1表示已充值; 2表示充值失败;
        $supplierStatusMap = [
            1 => 3, // 1已充值 --> 3充值成功
            2 => 99, // 2充值失败 --> 充值失败，等待重试
        ];
        $supplierStatus = $supplierStatusMap[$params['state']] ?? 2;
        if ($order['supplier_status'] == $supplierStatus) {
            Db::name('mobile_notify')->insert($insert);

            return 'success';
        }
        $update = [
            'supplier_order_no' => $params['order_number'],
            'supplier_status' => $supplierStatus,
        ];
        if ($supplierStatus == 99) {
            // $update['refund_status'] = 2;   // 充值失败，退款
            $order['notify_url'] = '';  // 失败通知先不发
        }
        if (!empty($params['otime'])) {
            $update['finish_time'] = $params['otime'];
        }

        Db::name('mobile_notify')->insert($insert);

        Db::startTrans();
        try {
            // 如果是返佣模式，将订单结算方式改成待结算
            if ($supplierStatus == 3 && $order['settle_type'] == SETTLE_TYPE_PROFIT) {
                if ($order['profit'] == 0) {
                    $update['settle_status'] = 3;
                } elseif ($order['settle_status'] == 1) {
                    $update['settle_status'] = 2;
                }
            }

            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $insert['result'] = '订单更新失败' . $order['id'] . '。' . $e->getMessage();
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        return 'success';
    }
}
